package com.blog.controller;

import java.io.BufferedWriter;
import java.io.File;
import java.io.FileOutputStream;
import java.io.FileWriter;
import java.io.IOException;
import java.io.OutputStreamWriter;
import java.lang.reflect.InvocationTargetException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.apache.commons.beanutils.BeanUtils;
import org.apache.commons.io.FileUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.blog.bean.Blog;
import com.blog.bean.BlogMsg;
import com.blog.bean.Discuss;
import com.blog.bean.Record;
import com.blog.bean.User;
import com.blog.dao.IBlogDao;
import com.blog.dao.IDiscussDao;
import com.blog.dao.IPraiseDao;
import com.blog.dao.IRecordDao;
import com.blog.dao.IUserDao;

/**
 * @className: BlogController
 * @description: 
 * @author: HCl
 * @createTime: 2020年6月7日 下午12:38:10
 */
@Controller
public class BlogController {

	@Autowired 
	private IBlogDao blogDao;
	@Autowired
	private IDiscussDao discussDao;
	@Autowired
	private IPraiseDao praiseDao;
	@Autowired
	private IRecordDao recordDao;
	@Autowired
	private IUserDao userDao;
	
	@RequestMapping(value = "searchBlog")
	public String searchBlog(HttpSession session,HttpServletRequest request) {
		String type = "";
		String title = "";
		type = (request.getParameter("type")!=null)?request.getParameter("type"):"";
		title = (request.getParameter("title")!=null)?request.getParameter("title"):"";  
		
		if (type.trim().equals("") && title.trim().equals("")) {
			return "redirect:index";
		} else if( type.trim().equals("") && !title.trim().equals("")){

			List<Blog> allBlogs = blogDao.selectBlogByTitle(title,"");
			List<BlogMsg> blogMsgs = new LinkedList<BlogMsg>();
			 
			for (int i = 0; i < allBlogs.size(); i++) {  
				
				int praise = praiseDao.selectBlogPraiseByBlogId(allBlogs.get(i).getId());
				int recordnum = recordDao.selectRecordByBlogId(allBlogs.get(i).getId());
				int dicussnum = discussDao.selectBlogDiscussById(allBlogs.get(i).getId()).size();
				BlogMsg blogMsg = new BlogMsg(praise, recordnum, dicussnum);
				blogMsgs.add(blogMsg);
			}
			session.setAttribute("all_blog_list", allBlogs);
			session.setAttribute("all_blog_list_msg", blogMsgs);
			
			return "searchBlog";  
		}else if(!type.trim().equals("") && title.trim().equals("")){ 

			List<Blog> allBlogs = blogDao.selectBlogByType(type);
			List<BlogMsg> blogMsgs = new LinkedList<BlogMsg>();
			 
			for (int i = 0; i < allBlogs.size(); i++) {
				
				int praise = praiseDao.selectBlogPraiseByBlogId(allBlogs.get(i).getId());
				int recordnum = recordDao.selectRecordByBlogId(allBlogs.get(i).getId());
				int dicussnum = discussDao.selectBlogDiscussById(allBlogs.get(i).getId()).size();
				BlogMsg blogMsg = new BlogMsg(praise, recordnum, dicussnum);
				blogMsgs.add(blogMsg);
			}
			session.setAttribute("all_blog_list", allBlogs);
			session.setAttribute("all_blog_list_msg", blogMsgs);
			
			return "searchBlog";
		}else {
			List<Blog> allBlogs = blogDao.selectBlogByTypeAndTitle(type, title);
			List<BlogMsg> blogMsgs = new LinkedList<BlogMsg>();
			 
			for (int i = 0; i < allBlogs.size(); i++) {
				
				int praise = praiseDao.selectBlogPraiseByBlogId(allBlogs.get(i).getId());
				int recordnum = recordDao.selectRecordByBlogId(allBlogs.get(i).getId());
				int dicussnum = discussDao.selectBlogDiscussById(allBlogs.get(i).getId()).size();
				BlogMsg blogMsg = new BlogMsg(praise, recordnum, dicussnum);
				blogMsgs.add(blogMsg);
			}
			session.setAttribute("all_blog_list", allBlogs);
			session.setAttribute("all_blog_list_msg", blogMsgs);
			
			return "searchBlog";
		}
		
	}
	@RequestMapping(value = "userBlog")
	public String userBlog(HttpSession session,HttpServletRequest request) {
		
		User user = (User)session.getAttribute("loginUser");
		if (user == null) {
			return "redirect:login";
		} else {
			
			//查询user所有博客
			List<Blog> allBlogs = blogDao.selectBlogByUserId(user.getId());
			
			//
			List<BlogMsg> blogMsgs = new LinkedList<BlogMsg>();
			
			for (int i = 0; i < allBlogs.size(); i++) {
				
				int praise = praiseDao.selectBlogPraiseByBlogId(allBlogs.get(i).getId());
				int recordnum = recordDao.selectRecordByBlogId(allBlogs.get(i).getId());
				int dicussnum = discussDao.selectBlogDiscussById(allBlogs.get(i).getId()).size();
				BlogMsg blogMsg = new BlogMsg(praise, recordnum, dicussnum);
				blogMsgs.add(blogMsg);
			}
			
			 
			//设置session
			session.setAttribute("user_blog_list", allBlogs);
			session.setAttribute("user_blog_list_msg", blogMsgs);
			
			
		}
		
		return "userBlog";
	}
	
	@RequestMapping(value = "createBlog")
	public String createBlog(HttpSession session,HttpServletRequest request) {
		User user = (User)session.getAttribute("loginUser");
		if (user == null) {
			return "redirect:login";
		} else {
			return "createBlog";
		}
		
	}
	
	@RequestMapping(value = "saveHtml")
	@ResponseBody
	public Map<String, Object> saveHtml(String text,HttpSession session) {
		String blogUrl = "";
		Map<String, Object> reMap = new HashMap<String, Object>();
		User user =(User)session.getAttribute("loginUser");
		
		if (user == null) {
			reMap.put("state", 0);
			reMap.put("url", "login");
		} else {

			String htmlScript = "<script>table {border-top: 1px solid #ccc;border-left: 1px solid #ccc;}\r\n" + 
					"table td,table th {border-bottom: 1px solid #ccc;border-right: 1px solid #ccc;padding: 3px 5px;}\r\n" + 
					"table th {border-bottom: 2px solid #ccc;text-align: center;}/* blockquote 样式 */blockquote {display: block;\r\n" + 
					"border-left: 8px solid #d0e5f2;padding: 5px 10px;margin: 10px 0;line-height: 1.4;font-size: 100%;background-color: #f1f1f1;\r\n" + 
					"}/* code 样式 */code {display: inline-block;*display: inline;*zoom: 1;background-color: #f1f1f1;border-radius: 3px;\r\n" + 
					"padding: 3px 5px;margin: 0 3px;}pre code {display: block;}/* ul ol 样式 */ul, ol {margin: 10px 0 10px 20px;}</script>";
			
			String html = htmlScript + text;
			
			Date d = new Date();
			//SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");	
			SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyyMMddHHmmss");
			String sdf = simpleDateFormat.format(d);
			
			String pathString = "D:\\environment\\apache\\apache-tomcat-8.5.50\\webapps\\upload\\myblog\\"+user.getId()+"\\"+sdf;
			
			System.out.println(text.toString());
			try {
				FileUtils.writeStringToFile(new File(pathString+"\\"+user.getId()+"_"+sdf+".txt"), new String(html),"utf-8") ;
				
				blogUrl = "/upload/myblog/"+user.getId()+"/"+sdf+"/"+user.getId()+"_"+sdf+".txt";
				reMap.put("state", 1);
				reMap.put("url", blogUrl);
				return reMap;
			} catch (Exception e) {
				// TODO: handle exception
			}
		}
		
		
		
		reMap.put("state", 2);
		reMap.put("msg","未知错误！");
		return reMap;
	}
	
	@RequestMapping(value = "addBlog")
	@ResponseBody
	public Map<String, Object> addBlog(HttpServletRequest request,HttpSession session){
		Map<String, Object> reMap = new HashMap<String, Object>();
		User user =(User)session.getAttribute("loginUser");
		if (user == null) {
			reMap.put("state", 0);
			reMap.put("msg", "您未登录！");
		} else {

			Date d = new Date();
			SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
			String sdf = simpleDateFormat.format(d);
			
			
	        Blog blog = new Blog();
	        blog.setTitle(request.getParameter("title"));
	        blog.setDescribe(request.getParameter("describe"));
	        blog.setContenturl(request.getParameter("contenturl"));
	        blog.setType(request.getParameter("type"));
	        blog.setPower(Integer.parseInt(request.getParameter("power")));
			blog.setCreatedate(sdf);
			blog.setPublisher(user.getId());
	        blog.setState(1);
	        
	        blogDao.addBlog2(blog);
	        
		}
		
		
		
		return reMap;
		
		
	}
	
	
	@RequestMapping(value = "showBlog")
	public String showBlog(HttpSession session,HttpServletRequest request) {
		
		int id = 0;
		try {
			id = Integer.parseInt(request.getParameter("id"));
		} catch (Exception e) {
			// TODO: handle exception
		}
		if (id == 0) {
			return "redirect:index"; 
		} 
		String noContent = "<div><h1>页面没有找到！</h1></div>";
		
		Blog blog = blogDao.selectBlogById(id);
		if (blog == null) {
			session.setAttribute("blog_contenturl_"+id, noContent);
		} else {
			//保存用户浏览记录
			User user = (User) session.getAttribute("loginUser");
			
			if (user == null) {
				//不保存记录
			} else {
				
				Date d = new Date();
				SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
				String sdf = simpleDateFormat.format(d);
				
				//保存记录 
				Record record = new Record();
				record.setBlog(blog.getId()); 
				record.setFrom(user.getId());
				record.setTime(sdf);
				Record inRecord =recordDao.selectRecordByUserIdAndBlogId(record);
				if (inRecord == null) {
					int x = recordDao.addRecord(record); 
				} else {
					record.setId(inRecord.getId());
					int x = recordDao.updateRecord(record);
				}
				
				
				//更新最近访问
				List<Record> records = recordDao.selectAllRecordByUserId(user.getId());
				List<Blog> historyBlogs = new LinkedList<Blog>(); 
				Blog tempBlog ;
				for (int i = 0; i < records.size(); i++) {
					tempBlog = new Blog();
					tempBlog = blogDao.selectBlogById(records.get(i).getBlog());
					if (tempBlog == null) {
						continue; 
					}
					tempBlog.setCreatedate(records.get(i).getTime().toString()); 
					historyBlogs.add(tempBlog);
					if(i == 4)break;
					
					
				}
				session.setAttribute("history_blog", historyBlogs);

			} 
			
			//查找博主
			User publisherUser = userDao.selectUserById(blog.getPublisher());
			session.setAttribute("blog_publisher_"+id, publisherUser);

			
			int praise = praiseDao.selectBlogPraiseByBlogId(id);
			
		 
			List<Discuss> discusses = discussDao.selectBlogDiscussById(id);
			
			int recordnum = recordDao.selectRecordByBlogId(id);
			
			session.setAttribute("blog_praise_"+id, praise);
			session.setAttribute("blog_"+id, blog);
			session.setAttribute("blog_discuss_list_"+id, discusses);
			session.setAttribute("blog_record_"+id, recordnum);
			
			
			
		}
		
		
		
		
		
		return "showBlog";
	}
	
	@RequestMapping(value = "otherBlog")
	public String otherBlog(HttpSession session,HttpServletRequest request) {
		
		
		
		int id = 0;
		
		try {
			id = Integer.parseInt(request.getParameter("id"));
		} catch (Exception e) {
			// TODO: handle exception
		}
		User loginUser = (User)session.getAttribute("loginUser");
		if (loginUser != null) {
			if (loginUser.getId() == id) {
				return "redirect:userBlog"; 
			}
		}
		
		if (id == 0) {
			//跳转index
			return "redirect:index";
		} else {

			User user = userDao.selectUserById(id);
			if (user == null) {
				return "redirect:index";
			} else {
				
				//查询user所有博客
				List<Blog> allBlogs = blogDao.selectBlogByUserId(user.getId());
				//获取博客点赞等信息
				List<BlogMsg> blogMsgs = new LinkedList<BlogMsg>();
				
				for (int i = 0; i < allBlogs.size(); i++) {
					
					int praise = praiseDao.selectBlogPraiseByBlogId(allBlogs.get(i).getId());
					int recordnum = recordDao.selectRecordByBlogId(allBlogs.get(i).getId());
					int dicussnum = discussDao.selectBlogDiscussById(allBlogs.get(i).getId()).size();
					BlogMsg blogMsg = new BlogMsg(praise, recordnum, dicussnum);
					blogMsgs.add(blogMsg);
				}
				
				//设置session
				session.setAttribute("user_blog_list_"+id, allBlogs);
				session.setAttribute("user_blog_list_msg", blogMsgs); 
				session.setAttribute("user_"+id, user);
				return "otherBlog"; 
				
			}
		}
	
		
		
		
	}
	
	@RequestMapping(value = "deleteBlogById")
	@ResponseBody
	public Map<String, Object> deleteBlogById(int id,HttpSession session){
		
		int i = blogDao.deleteBlogById(id);
		
		return new HashMap<String, Object>();
	}
}
